//一.socket 发送消息
//1. 给本次连接发送消息
//socket.emit()
//2. 给某个房间内所有人发消息
//io.in(room).emit()
//3. 除本连接外  给某个房间内所有人发消息
//socket.to(room).emit()
//4 .除本连接外 给所有人发送消息
//socket.broadcast.emit()

//二.socket.io
//1.socket.io 是socket的超集
//2.socket.io 有房间的概念
//3.socket.io 跨平台 跨终端 跨语言

const { Server } = require("socket.io");
const log4js = require("log4js");
log4js.configure({
  appenders: {
    file: {
      type: "file",
      filename: "app.log",
      layout: {
        type: "pattern",
        pattern: "%r %p - %m",
      },
    },
  },
  categories: {
    default: {
      appenders: ["file"],
      level: "debug",
    },
  },
});
const logger = log4js.getLogger("cheese");

const USER = 3;//房间上限

function socketStart(https) {
  try {
    const io = new Server(https, { cors: true });
    //连接
    io.on("connection", (socket) => {
      socket.emit("connection", "您已连接上socket.io!!!");
      //加入房间
      socket.on("jion", (room) => {
        console.log(
          "++++++++++++++++++Someone join room number++++++++++++++++：",
          room
        );
        socket.join(room);
        const myRoom = io.sockets.adapter.rooms.get(room);
        const user = myRoom.size;
        console.log(
          `++++++++++++++++++the number of users in room:${room}: ${user}user`
        );
        logger.log("the number of users in room:", user);

        if (user < USER) {
          socket.emit("jioned", room, socket.id);
          if (user > 1) {
            console.log("otherjion");
            socket.to(room).emit("otherjion", room, socket.id);
          }
        } else {
          socket.leave(room);
          socket.emit("full", room, socket.id);
        }
      });
      //离开房间
      socket.on("leave", (room) => {
        const myRoom = io.sockets.adapter.rooms.get(room);
        if (myRoom.size) {
          const user = myRoom.size;
          logger.log("the number of users in room:", user - 1);
          socket.emit("leaved", room, socket.id);
          socket.to(room).emit("bye", room, socket.id);
          socket.leave(room);
          console.log(`${room} has one leave, ${myRoom.size} people in room:`, myRoom);
        }
      });
      //给对方发送消息
      socket.on("message", (room, data) => {
        socket.to(room).emit("message", room, data);
      });
    });
  } catch (err) {
    console.log(err);
  }
}

module.exports = socketStart;
